#include <iostream>
#include <unistd.h>
using namespace std;
#include <sys/types.h>
#include <sys/wait.h>
#include <string>

int main()
{
    int fds[2] = {0};
    int tmp = pipe(fds);
    if (tmp != 0)
    {
        cerr << "pipe error" << endl;
        return 0;
    }
    pid_t id = fork();
    if (id < 0)
    {
        perror("进程创建的错误");
        return 0;
    }
    else if (id == 0) // 子进程
    {
        close(fds[0]);

        int count = 0;
        while (true)
        {
            string message = "hello ss  ";
            message += to_string(getpid());
            message += "   ";
            message += to_string(count);
            write(fds[1], message.c_str(), message.size());
            count++;
            sleep(1);
        }
    }
    else
    {
        close(fds[1]);
        char buffer[1024];

        while (true)
        {
            ssize_t len = read(fds[0], buffer, 1024);
            if (len > 0)
            {
                buffer[len] = 0;
                cout << "child->father" << buffer << endl;
            }
            else if (len == 0)
            {
                cout << "写端已经不再往进写了" << endl;
                break;
            }
        }
        int status = 0;
        pid_t rid = waitpid(id, &status, 0);
        std::cout << "father wait child success: " << rid << " exit code: " << ((status << 8) & 0xFF) << ", exit sig: " << (status & 0x7F) << std::endl;
    }
}